/*
public class Test3 {
}
*/
public class Test3 {
    public static int matrixChainOrder(int[] p) {
        int n = p.length - 1;
        int[][] dp = new int[n + 1][n + 1];
        int[][] s = new int[n + 1][n + 1]; // 记录分割点

        for (int len = 2; len <= n; len++) {
            for (int i = 1; i <= n - len + 1; i++) {
                int j = i + len - 1;
                dp[i][j] = Integer.MAX_VALUE;
                for (int k = i; k < j; k++) {
                    int cost = dp[i][k] + dp[k + 1][j] + p[i - 1] * p[k] * p[j];
                    if (cost < dp[i][j]) {
                        dp[i][j] = cost;
                        s[i][j] = k;
                    }
                }
            }
        }

        // 打印最优括号化方案
        printOptimalParens(s, 1, n);
        System.out.println();

        return dp[1][n];
    }

    public static void printOptimalParens(int[][] s, int i, int j) {
        if (i == j) {
            System.out.print("A" + i);
        } else {
            System.out.print("(");
            printOptimalParens(s, i, s[i][j]);
            printOptimalParens(s, s[i][j] + 1, j);
            System.out.print(")");
        }
    }

    public static void main(String[] args) {
        // p 表示矩阵的维度，p[i-1]和p[i]分别是第i个矩阵的行数和列数
        int[] p = {30, 35, 15, 5, 10, 20, 25};
        int minMultiplications = matrixChainOrder(p);
        System.out.println("最少乘法次数：" + minMultiplications);
    }
}